import * as mqtt from 'mqtt/dist/mqtt.min.js'
import Hashids from 'hashids'
export function getClient(client: any) {
  console.log(5165565 + '============')
  const nowTime = new Date()
  const codeArray = [
    nowTime.getHours(),
    nowTime.getMinutes(),
    nowTime.getSeconds(),
    nowTime.getMilliseconds(),
  ]
  const hashids = new Hashids()
  const id_left = hashids.encode(codeArray)
  const id_right = nowTime.getTime() % 10000000
  // 测试服
  // const mqtt_ws_url = 'ws://47.113.81.214:1885/mqtt'
  // 正式服
  const mqtt_ws_url = 'wss://video.cvww.net:1887/mqtt'
  const mqttConfig = {
    clientId: id_left + id_right, // client标识
    clean: true,
    reconnectPeriod: 1000, // 1000毫秒，两次重新连接之间的间隔
    // connectTimeout: 30 * 1000, // 1000毫秒，两次重新连接之间的间隔
    // resubscribe: true // 如果连接断开并重新连接，则会再次自动订阅已订阅的主题（默认true）
    username: 'wangqi',
    password: '123456',
  }
  client = mqtt.connect(mqtt_ws_url, mqttConfig)
  return client
}
/**
 * mqtt 订阅
 * client mqtt连接对象
 * topics 需要订阅的主题
 * callbackFunc 订阅成功回调函数
 */
export function subscribe(client: any, topics: any, callbackFunc: any) {
  if (topics) {
    if (typeof topics == 'string') {
      topics = topics.split(',')
    }
    for (let k = 0; k < topics.length; k++) {
      const topic = topics[k]
      setTimeout(() => {
        client.subscribe(topic, { qos: 2 }, (err: Error) => {
          if (typeof callbackFunc == 'function') {
            callbackFunc(topic, err)
          }
        })
      }, 200 * k)
    }
  } else {
    console.log('订阅主题不存在')
    callbackFunc(topics, 404)
  }
}
/**
 * mqtt 取消订阅
 * client mqtt连接对象
 * topics 需要取消订阅的主题
 * callbackFunc 订阅成功回调函数
 */
export function unsubscribe(client: any, topics: any, callbackFunc: any) {
  if (topics) {
    if (typeof topics == 'string') {
      topics = topics.split(',')
    }
    for (let k = 0; k < topics.length; k++) {
      const topic = topics[k]
      setTimeout(() => {
        client.unsubscribe(topic, { qos: 2 }, (err: Error) => {
          if (typeof callbackFunc == 'function') {
            callbackFunc(topic, err)
          }
        })
      }, 200 * k)
    }
  } else {
    console.log('退订阅主题不存在')
  }
}
